"""
数据库初始化修复脚本
解决 isinstance() arg 2 类型错误问题
"""

import asyncio
import logging
from sqlalchemy.orm import relationship
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s')
logger = logging.getLogger(__name__)

# 创建自定义基类
Base = declarative_base()

async def init_db(db_url):
    """初始化数据库连接"""
    logger.info(f"初始化数据库: {db_url}")
    
    # 创建异步引擎 - SQLite专用配置
    if db_url.startswith('sqlite'):
        logger.info("检测到SQLite数据库，应用专用配置...")
        engine = create_async_engine(
            db_url,
            echo=False,
            connect_args={"check_same_thread": False}
        )
    else:
        engine = create_async_engine(
            db_url,
            echo=False,
            pool_pre_ping=True
        )
    
    # 创建会话工厂
    async_session_factory = async_sessionmaker(
        engine,
        class_=AsyncSession,
        expire_on_commit=False
    )
    
    return engine, async_session_factory

async def create_tables(engine):
    """创建表 - 修复版本"""
    try:
        # 导入所有模型
        from app.models import audiobook, voice_profile, audio_stream, user, task
        
        # 直接创建表，避免手动检查关系
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
        
        logger.info("数据库表创建成功")
        return True
    except Exception as e:
        logger.error(f"创建数据库表失败: {str(e)}")
        return False

async def main():
    """主函数"""
    logger.info("数据库修复工具启动")
    
    # 数据库配置
    db_url = "sqlite+aiosqlite:///./data/app.db"
    
    # 初始化数据库
    engine, session_factory = await init_db(db_url)
    
    # 注入引擎和会话工厂
    import app.core.database
    app.core.database.engine = engine
    app.core.database.async_session_factory = session_factory
    app.core.database.Base = Base
    
    # 创建表
    success = await create_tables(engine)
    if success:
        logger.info("数据库修复完成，现在可以启动应用了")
    else:
        logger.error("数据库修复失败")

if __name__ == "__main__":
    asyncio.run(main())